package com.ganlucode.sipmock.sip.request.impl;

import com.ganlucode.sipmock.sip.request.ISipRequestProcessor;
import com.ganlucode.sipmock.utils.SipHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sip.RequestEvent;
import javax.sip.ServerTransaction;
import javax.sip.header.ExpiresHeader;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;
import javax.sip.message.Request;
import javax.sip.message.Response;

/**
 * @author GanLu
 */
@Slf4j
@Service("subscribeRequestProcessor")
public class SubscribeRequestProcessor implements ISipRequestProcessor {

	@Autowired
	private SipHelper sipHelper;
	@Autowired
	private HeaderFactory headerFactory;
	@Autowired
	private MessageFactory messageFactory;

	/**   
	 * 处理SUBSCRIBE请求  
	 * 
	 * @param evt
	 */
	@Override
	public void process(RequestEvent evt) throws Exception{
		Request request = evt.getRequest();

		Response response = null;
		response = messageFactory.createResponse(200, request);
		if (response != null) {
			ExpiresHeader expireHeader = headerFactory.createExpiresHeader(30);
			response.setExpires(expireHeader);
		}
		log.info("response : {}", response.toString());
		ServerTransaction transaction = sipHelper.createServerTransaction(evt);
		if (transaction != null) {
			transaction.sendResponse(response);
			transaction.terminate();
		} else {
			log.info("processRequest serverTransactionId is null.");
		}
		
	}

}
